#!/usr/bin/python
#=======================================
# Link Hot Backup Checker 
#=======================================

import os
import sys
import string

class CheckLink:
    def __init__(self):
        pass
    def w32_check(self,flag,TIMES):
        self.flag = flag
        res = os.popen('ping %s -n %s -l 32 -w 20' % (self.flag,TIMES))
        for x in res.readlines():
            if string.find(x,'    Packets:'):
                pass
            else:
                return x.split(',')[1].split('=')[1].lstrip()
    def linux2_check(self,flag,interface,TIMES):
    	self.flag = flag
    	res = os.popen('ping %s -c %s -i 2 -W 2 -I %s' % (self.flag,TIMES,interface))
	#print res.readlines()
	for x in res.readlines():
		if ' received' in x:
			return x.split(',')[1].lstrip().split()[0]
		else :
		        pass
																

def set_interface(up_interface,down_interface):
	# remove down interface route
	os.popen('route del default gw %s dev %s' % (down_interface['route'],down_interface['interface']))
	# ifconfig down false interface
	os.popen('ifconfig %s down' % down_interface['interface'])
	#### remove false interface router
	#### os.popen('route del default gw %s dev %s' % (down_interface['route'],down_interface['interface']))
	#ifconfig up good interface
	os.popen('ifconfig %s %s netmask %s' % (up_interface['interface'],up_interface['ip'],up_interface['netmask']))
	#add good interface route 
	os.popen('route add default gw %s dev %s' % (up_interface['route'],up_interface['interface']))
	## Setting Firewall
	os.popen('%s' % up_interface['firewall'])

def main ():
    flag = CheckLink()
    MASTER['stats'] = flag.linux2_check(MASTER['flag'],MASTER['interface'],FLAG_TIMES)
    BACKUP['stats'] = flag.linux2_check(BACKUP['flag'],BACKUP['interface'],FLAG_TIMES)
    print MASTER['stats'],BACKUP['stats']
    if MASTER['stats'] == str(FLAG_TIMES):
    	   print 'First Check Master link'
           CURRENT_LINK = 'MASTER' 
    elif BACKUP['stats'] == str(FLAG_TIMES):
    	   print 'First Check Backup link'
           CURRENT_LINK = 'BACKUP'
    else :
           CURRENT_LINK = 'UNKNOW'
    while 1:
        if CURRENT_LINK == 'MASTER':
            MASTER['stats'] = flag.linux2_check(MASTER['flag'],MASTER['interface'],FLAG_TIMES)
            if MASTER['stats'] != str(FLAG_TIMES):
                set_interface(BACKUP,MASTER)
                print 'Master False ,set BACKUP LINK UP'
                CURRENT_LINK = 'BACKUP'
            else :
                print 'Master GOOD'
        elif CURRENT_LINK == 'BACKUP':
            BACKUP['stats'] = flag.linux2_check(BACKUP['flag'],BACKUP['interface'],FLAG_TIMES)
            if BACKUP['stats'] != str(FLAG_TIMES):
                set_interface(MASTER,BACKUP)
                print 'Backup False ,set MASTER LINK UP'
                CURRENT_LINK = 'MASTER'
            else :
                print 'Backup GOOD'
        elif CURRENT_LINK == 'UNKNOW':
		MASTER['stats'] = flag.linux2_check(MASTER['flag'],MASTER['interface'],FLAG_TIMES)
		BACKUP['stats'] = flag.linux2_check(BACKUP['flag'],BACKUP['interface'],FLAG_TIMES)
		if MASTER['stats'] == str(FLAG_TIMES):
		        CURRENT_LINK = 'MASTER'
		elif BACKUP['stats'] == str(FLAG_TIMES):
		        CURRENT_LINK = 'BACKUP'
		else :
		       CURRENT_LINK = 'UNKNOW'
		print "UNKNOW STATs ,maybe all interface DOWN !!check it again"
            
    
if __name__ == '__main__':
        
        global OS
        global FLAG_TIMES
        global CURRENT_LINK
        
        global MASTER
        global BACKUP
        
        MASTER = {'ip' : '218.95.229.24',
            'route' : '218.95.229.1',
            'netmask' : '255.255.255.224',
            'interface' : 'eth1',
            'flag' : '218.95.229.1',
            'firewall' : '/etc/rc.d/rc.fw.master',
            'stats' : '',}
        
        BACKUP = {'ip' : '218.95.236.38',
            'route' : '218.95.236.37',
            'netmask' : '255.255.255.252',
            'interface' : 'eth2',
            'flag' : '218.95.236.37',
            'firewall' : '/etc/rc.d/rc.fw.backup',
            'stats' : ''}  
            
        CURRENT_LINK = ''  
            
        OS = sys.platform
        FLAG_TIMES = 2
        main()
